package com.sprucetec.common.config;

import com.mongodb.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Administrator
 * @Date 2018/11/8 17:44
 **/
@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "mongodb")
public class MongoDBConfig extends AbstractMongoConfiguration {

    @Value("${mongodb.database}")
    private String database;
    @Value("#{'${mongodb.mongodbNode}'.split(',')}")
    private String[] mongodbNode; 	//sentinel 集群节点

    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        List<ServerAddress> seeds = new ArrayList<ServerAddress>();
        for (String mongodbNodes : mongodbNode) {
            String host = mongodbNodes.split(":")[0];
            int port = Integer.parseInt(mongodbNodes.split(":")[1]);
            seeds.add(new ServerAddress(host,port));
        }
        return new MongoClient(seeds);
    }


    //方法一
//    @Bean
//    @Autowired
//    public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) throws UnknownHostException {
//        //String uriStr = "mongodb://"+properties.getUserName()+":"+properties.getPassword()+"@"+properties.getUri()+"/"+properties.getDatabaseName();
//        String uriStr = "mongodb://"+properties.getUri()+"/"+properties.getDatabaseName();
//        System.out.println(uriStr);
//        MongoClientURI mongoClientURI = new MongoClientURI(uriStr);
//        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClientURI);
//        return mongoDbFactory;
//    }

//    @Bean
//    @Autowired
//    public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) {
//        //客户端配置（连接数，副本集群验证）
//        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//        builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
//        builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
//        if (properties.getReplicaSet() != null) {
//            builder.requiredReplicaSetName(properties.getReplicaSet());
//        }
//
//        builder.threadsAllowedToBlockForConnectionMultiplier(properties.getThreadsAllowedToBlockForConnectionMultiplier());
//        builder.serverSelectionTimeout(properties.getServerSelectionTimeout());
//        builder.maxWaitTime(properties.getMaxWaitTime());
//        builder.maxConnectionIdleTime(properties.getMaxConnectionIdleTime());
//        builder.maxConnectionLifeTime(properties.getMaxConnectionLifeTime());
//        builder.connectTimeout(properties.getConnectTimeout());
//        builder.socketTimeout(properties.getSocketTimeout());
//        //builder.socketKeepAlive(properties.getSocketKeepAlive());
//        builder.sslEnabled(properties.getSslEnabled());
//        builder.sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed());
//        builder.alwaysUseMBeans(properties.getAlwaysUseMBeans());
//        builder.heartbeatFrequency(properties.getHeartbeatFrequency());
//        builder.minHeartbeatFrequency(properties.getMinHeartbeatFrequency());
//        builder.heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout());
//        builder.heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout());
//        builder.localThreshold(properties.getLocalThreshold());
//        MongoClientOptions mongoClientOptions = builder.build();
//        // MongoDB地址列表
//        List<ServerAddress> serverAddressList = new ArrayList<>();
//        for (String address : properties.getAddress()) {
//            String[] hostAndPort = address.split(":");
//            String host = hostAndPort[0];
//            Integer port = Integer.parseInt(hostAndPort[1]);
//            ServerAddress serverAddress = new ServerAddress(host, port);
//            serverAddressList.add(serverAddress);
//        }
//        // 连接认证
////        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUserName(),
////            properties.getDatabaseName(),
////            properties.getPassword().toCharArray());
//        //创建客户端和Factory
//        MongoClient mongoClient = new MongoClient(serverAddressList,mongoClientOptions);
//        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, properties.getDatabaseName());
//        return mongoDbFactory;
//    }

}
